import {
  SET_USERINFO, SET_AUTHTOKEN, SET_AUTHINFO, SET_ROUTERS, SET_LOADASYNCROUTER_FLAG
} from '../mutations'
import auth from '@/api/auth'
import {resetRouter} from '@/router'
import system from '@/api/system'
import {addAuthToken, removeAuth} from '@/utils/auth'
import {setCacheLoginUserInfo, setCacheAuthInfoInfo} from '@/utils/cache'
const user = {
  namespaced: true,
  state: {
    userInfo: {},
    authInfo: {},
    loadAsyncRouterFlag: false,
    avatar: '',
    crmRouters: []
  },
  mutations: {
    [SET_LOADASYNCROUTER_FLAG]: (state, data) => {
      state.loadAsyncRouterFlag = data
    },
    [SET_AUTHTOKEN]: (state, data) => {
      // 请求头添加Token
      addAuthToken(data)
    },
    [SET_USERINFO]: (state, userInfo) => {
      state.userInfo = userInfo
      state.avatar = userInfo ? userInfo.avatar : ''
      setCacheLoginUserInfo(userInfo)
    },
    [SET_AUTHINFO]: (state, authInfo) => {
      state.authInfo = authInfo
      setCacheAuthInfoInfo(authInfo)
    },
    [SET_ROUTERS]: (state, data) => {
      state.crmRouters = data.router.crm
    }
  },
  actions: {
    Login ({commit, dispatch}, loginInfo) {
      return new Promise((resolve, reject) => {
        auth.loginAPI(loginInfo).then(res => {
          commit(SET_AUTHTOKEN, res.data)
          resolve(res)
        }).catch((error) => {
          reject(error)
        })
      })
    },
    ChangeLogin ({commit, dispatch}, params) {
      return new Promise((resolve, reject) => {
        auth.changeLoginAPI(params).then(res => {
          resetRouter()
          removeAuth().then(() => {
            commit(SET_AUTHTOKEN, res.data)
            resolve(res)
          })
        }).catch((error) => {
          reject(error)
        })
      })
    },
    GetLoginInfo ({commit, dispatch}) {
      return new Promise((resolve, reject) => {
        auth.getLoginInfoAPI().then(res => {
          const {userInfo} = res.data
          commit(SET_USERINFO, userInfo)
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    GetUserMenuInfo ({commit}, params) {
      return new Promise((resolve, reject) => {
        const {employeeCode, positionCode} = params
        system.getUserMenuAPI(employeeCode, positionCode).then(res => {
          commit(SET_AUTHINFO, res.data)
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    Logout () {
      return new Promise((resolve, reject) => {
        auth.logoutAPI().then(res => {
          removeAuth()
          resetRouter()
          resolve(res)
        }).catch((error) => {
          removeAuth()
          resetRouter()
          reject(error)
        })
      })
    }
  }
}
export default user
